package com.example.demo.shiro.aop;

import com.example.demo.shiro.ShiroService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Modifier;

/**
 * @author zhaiding
 * @since 2019/6/1
 */
@Slf4j
@Aspect
@Component
public class RefreshFilterChainAspect {

    @Resource
    private ShiroService shiroService;

    /**
     * 配置切入点
     */
    @Pointcut(value = "@annotation(com.example.demo.shiro.annotation.RefreshFilterChain)")
    public void updateFilterChain() {
    }

    /**
     * 处理完请求后执行
     */
    @AfterReturning(value = "updateFilterChain()")
    public void doAfter() {
        // 动态刷新过滤链
        shiroService.updatePermission();
    }

    /**
     * 处理开始之前执行
     *
     * @param point 切点
     */
    @Before("updateFilterChain()")
    public void doBefore(JoinPoint point) {
        log.debug("updateFilterChain 开始工作!!!");

        System.out.println("目标方法名为:" + point.getSignature().getName());
        System.out.println("目标方法所属类的简单类名:" + point.getSignature().getDeclaringType().getSimpleName());
        System.out.println("目标方法所属类的类名:" + point.getSignature().getDeclaringTypeName());
        System.out.println("目标方法声明类型:" + Modifier.toString(point.getSignature().getModifiers()));
        //获取传入目标方法的参数
        Object[] args = point.getArgs();
        for (int i = 0; i < args.length; i++) {
            System.out.println("第" + (i + 1) + "个参数为:" + args[i]);
        }
        System.out.println("被代理的对象:" + point.getTarget());
        System.out.println("代理对象自己:" + point.getThis());

    }


    /**
     * 拦截异常操作
     *
     * @param joinPoint 切点
     * @param e         异常
     */
    @AfterThrowing(value = "updateFilterChain()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
        log.debug("updateFilterChain :", e);
    }

}
